<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/doc/src/examples/mandelbrot.qdoc -->
<head>
  <title>Qt 4.3: Mandelbrot Example</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td>
<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 align="center">Mandelbrot Example<br /><small></small></h1>
<p>Files:</p>
<ul>
<li><a href="threads-mandelbrot-mandelbrotwidget-cpp.html">threads/mandelbrot/mandelbrotwidget.cpp</a></li>
<li><a href="threads-mandelbrot-mandelbrotwidget-h.html">threads/mandelbrot/mandelbrotwidget.h</a></li>
<li><a href="threads-mandelbrot-renderthread-cpp.html">threads/mandelbrot/renderthread.cpp</a></li>
<li><a href="threads-mandelbrot-renderthread-h.html">threads/mandelbrot/renderthread.h</a></li>
<li><a href="threads-mandelbrot-main-cpp.html">threads/mandelbrot/main.cpp</a></li>
</ul>
<p>The Mandelbrot example shows how to use a worker thread to perform heavy computations without blocking the main thread's event loop.</p>
<p>The heavy computation here is the Mandelbrot set, probably the world's most famous fractal. These days, while sophisticated programs such as <a href="http://xaos.sourceforge.net/">XaoS</a> that provide real-time zooming in the Mandelbrot set, the standard Mandelbrot algorithm is just slow enough for our purposes.</p>
<p align="center"><img src="images/mandelbrot-example.png" alt="Screenshot of the Mandelbrot example" /></p><p>In real life, the approach described here is applicable to a large set of problems, including synchronous network I/O and database access, where the user interface must remain responsive while some heavy operation is taking place. The <a href="network-blockingfortuneclient.html">network/blockingfortuneclient</a> example shows the same principle at work in a TCP client.</p>
<p>The Mandelbrot application supports zooming and scrolling using the mouse or the keyboard. To avoid freezing the main thread's event loop (and, as a consequence, the application's user interface), we put all the fractal computation in a separate worker thread. The thread emits a signal when it is done rendering the fractal.</p>
<p>During the time where the worker thread is recomputing the fractal to reflect the new zoom factor position, the main thread simply scales the previously rendered pixmap to provide immediate feedback. The result doesn't look as good as what the worker thread eventually ends up providing, but at least it makes the application more responsive. The sequence of screenshots below shows the original image, the scaled image, and the rerendered image.</p>
<p><table align="center" cellpadding="2" cellspacing="1" border="0">
<tr valign="top" class="odd"><td><img src="images/mandelbrot_zoom1.png" /></td><td><img src="images/mandelbrot_zoom2.png" /></td><td><img src="images/mandelbrot_zoom3.png" /></td></tr>
</table></p>
<p>Similarly, when the user scrolls, the previous pixmap is scrolled immediately, revealing unpainted areas beyond the edge of the pixmap, while the image is rendered by the worker thread.</p>
<p><table align="center" cellpadding="2" cellspacing="1" border="0">
<tr valign="top" class="odd"><td><img src="images/mandelbrot_scroll1.png" /></td><td><img src="images/mandelbrot_scroll2.png" /></td><td><img src="images/mandelbrot_scroll3.png" /></td></tr>
</table></p>
<p>The application consists of two classes:</p>
<ul>
<li><tt>RenderThread</tt> is a <a href="qthread.html">QThread</a> subclass that renders the Mandelbrot set.</li>
<li><tt>MandelbrotWidget</tt> is a <a href="qwidget.html">QWidget</a> subclass that shows the Mandelbrot set on screen and lets the user zoom and scroll.</li>
</ul>
<p>If you are not already familiar with Qt's thread support, we recommend that you start by reading the <a href="threads.html">Thread Support in Qt</a> overview.</p>
<a name="renderthread-class-definition"></a>
<h2>RenderThread Class Definition</h2>
<p>We'll start with the definition of the <tt>RenderThread</tt> class:</p>
<pre> class RenderThread : public QThread
 {
     Q_OBJECT

 public:
     RenderThread(QObject *parent = 0);
     ~RenderThread();

     void render(double centerX, double centerY, double scaleFactor,
                 QSize resultSize);

 signals:
     void renderedImage(const QImage &amp;image, double scaleFactor);

 protected:
     void run();

 private:
     uint rgbFromWaveLength(double wave);

     QMutex mutex;
     QWaitCondition condition;
     double centerX;
     double centerY;
     double scaleFactor;
     QSize resultSize;
     bool restart;
     bool abort;

     enum { ColormapSize = 512 };
     uint colormap[ColormapSize];
 };</pre>
<p>The class inherits <a href="qthread.html">QThread</a> so that it gains the ability to run in a separate thread. Apart from the constructor and destructor, <tt>render()</tt> is the only public function. Whenever the thread is done rendering an image, it emits the <tt>renderedImage()</tt> signal.</p>
<p>The protected <tt>run()</tt> function is reimplemented from <a href="qthread.html">QThread</a>. It is automatically called when the thread is started.</p>
<p>In the <tt>private</tt> section, we have a <a href="qmutex.html">QMutex</a>, a <a href="qwaitcondition.html">QWaitCondition</a>, and a few other data members. The mutex protects the other data member.</p>
<a name="renderthread-class-implementation"></a>
<h2>RenderThread Class Implementation</h2>
<pre> RenderThread::RenderThread(QObject *parent)
     : QThread(parent)
 {
     restart = false;
     abort = false;

     for (int i = 0; i &lt; ColormapSize; ++i)
         colormap[i] = rgbFromWaveLength(380.0 + (i * 400.0 / ColormapSize));
 }</pre>
<p>In the constructor, we initialize the <tt>restart</tt> and <tt>abort</tt> variables to <tt>false</tt>. These variables control the flow of the <tt>run()</tt> function.</p>
<p>We also initialize the <tt>colormap</tt> array, which contains a series of RGB colors.</p>
<pre> RenderThread::~RenderThread()
 {
     mutex.lock();
     abort = true;
     condition.wakeOne();
     mutex.unlock();

     wait();
 }</pre>
<p>The destructor can be called at any point while the thread is active. We set <tt>abort</tt> to <tt>true</tt> to tell <tt>run()</tt> to stop running as soon as possible. We also call <a href="qwaitcondition.html#wakeOne">QWaitCondition::wakeOne</a>() to wake up the thread if it's sleeping. (As we will see when we review <tt>run()</tt>, the thread is put to sleep when it has nothing to do.)</p>
<p>The important thing to notice here is that <tt>run()</tt> is executed in its own thread (the worker thread), whereas the <tt>RenderThread</tt> constructor and destructor (as well as the <tt>render()</tt> function) are called by the thread that created the worker thread. Therefore, we need a mutex to protect accesses to the <tt>abort</tt> and <tt>condition</tt> variables, which might be accessed at any time by <tt>run()</tt>.</p>
<p>At the end of the destructor, we call <a href="qthread.html#wait">QThread::wait</a>() to wait until <tt>run()</tt> has exited before the base class destructor is invoked.</p>
<pre> void RenderThread::render(double centerX, double centerY, double scaleFactor,
                           QSize resultSize)
 {
     QMutexLocker locker(&amp;mutex);

     this-&gt;centerX = centerX;
     this-&gt;centerY = centerY;
     this-&gt;scaleFactor = scaleFactor;
     this-&gt;resultSize = resultSize;

     if (!isRunning()) {
         start(LowPriority);
     } else {
         restart = true;
         condition.wakeOne();
     }
 }</pre>
<p>The <tt>render()</tt> function is called by the <tt>MandelbrotWidget</tt> whenever it needs to generate a new image of the Mandelbrot set. The <tt>centerX</tt>, <tt>centerY</tt>, and <tt>scaleFactor</tt> parameters specify the portion of the fractal to render; <tt>resultSize</tt> specifies the size of the resulting <a href="qimage.html">QImage</a>.</p>
<p>The function stores the parameters in member variables. If the thread isn't already running, it starts it; otherwise, it sets <tt>restart</tt> to <tt>true</tt> (telling <tt>run()</tt> to stop any unfinished computation and start again with the new parameters) and wakes up the thread, which might be sleeping.</p>
<pre> void RenderThread::run()
 {
     forever {
         mutex.lock();
         QSize resultSize = this-&gt;resultSize;
         double scaleFactor = this-&gt;scaleFactor;
         double centerX = this-&gt;centerX;
         double centerY = this-&gt;centerY;
         mutex.unlock();</pre>
<p><tt>run()</tt> is quite a big function, so we'll break it down into parts.</p>
<p>The function body is an infinite loop which starts by storing the rendering parameters in local variables. As usual, we protect accesses to the member variables using the class's mutex. Storing the member variables in local variables allows us to minimize the amout of code that needs to be protected by a mutex. This ensures that the main thread will never have to block for too long when it needs to access <tt>RenderThread</tt>'s member variables (e.g&#x2e;, in <tt>render()</tt>).</p>
<p>The <tt>forever</tt> keyword is, like <tt>foreach</tt>, a Qt pseudo-keyword.</p>
<pre>         int halfWidth = resultSize.width() / 2;
         int halfHeight = resultSize.height() / 2;
         QImage image(resultSize, QImage::Format_RGB32);

         const int NumPasses = 8;
         int pass = 0;
         while (pass &lt; NumPasses) {
             const int MaxIterations = (1 &lt;&lt; (2 * pass + 6)) + 32;
             const int Limit = 4;
             bool allBlack = true;

             for (int y = -halfHeight; y &lt; halfHeight; ++y) {
                 if (restart)
                     break;
                 if (abort)
                     return;

                 uint *scanLine =
                         reinterpret_cast&lt;uint *&gt;(image.scanLine(y + halfHeight));
                 double ay = centerY + (y * scaleFactor);

                 for (int x = -halfWidth; x &lt; halfWidth; ++x) {
                     double ax = centerX + (x * scaleFactor);
                     double a1 = ax;
                     double b1 = ay;
                     int numIterations = 0;

                     do {
                         ++numIterations;
                         double a2 = (a1 * a1) - (b1 * b1) + ax;
                         double b2 = (2 * a1 * b1) + ay;
                         if ((a2 * a2) + (b2 * b2) &gt; Limit)
                             break;

                         ++numIterations;
                         a1 = (a2 * a2) - (b2 * b2) + ax;
                         b1 = (2 * a2 * b2) + ay;
                         if ((a1 * a1) + (b1 * b1) &gt; Limit)
                             break;
                     } while (numIterations &lt; MaxIterations);

                     if (numIterations &lt; MaxIterations) {
                         *scanLine++ = colormap[numIterations % ColormapSize];
                         allBlack = false;
                     } else {
                         *scanLine++ = qRgb(0, 0, 0);
                     }
                 }
             }

             if (allBlack &amp;&amp; pass == 0) {
                 pass = 4;
             } else {
                 if (!restart)
                     emit renderedImage(image, scaleFactor);
                 ++pass;
             }
         }</pre>
<p>Then comes the core of the algorithm. Instead of trying to create a perfect Mandelbrot set image, we do multiple passes and generate more and more precise (and computationally expensive) approximations of the fractal.</p>
<p>If we discover inside the loop that <tt>restart</tt> has been set to <tt>true</tt> (by <tt>render()</tt>), we break out of the loop immediately, so that the control quickly returns to the very top of the outer loop (the <tt>forever</tt> loop) and we fetch the new rendering parameters. Similarly, if we discover that <tt>abort</tt> has been set to <tt>true</tt> (by the <tt>RenderThread</tt> destructor), we return from the function immediately, terminating the thread.</p>
<p>The core algorithm is beyond the scope of this tutorial.</p>
<pre>         mutex.lock();
         if (!restart)
             condition.wait(&amp;mutex);
         restart = false;
         mutex.unlock();
     }
 }</pre>
<p>Once we're done with all the iterations, we call <a href="qwaitcondition.html#wait">QWaitCondition::wait</a>() to put the thread to sleep by calling, unless <tt>restart</tt> is <tt>true</tt>. There's no use in keeping a worker thread looping indefinitely while there's nothing to do.</p>
<pre> uint RenderThread::rgbFromWaveLength(double wave)
 {
     double r = 0.0;
     double g = 0.0;
     double b = 0.0;

     if (wave &gt;= 380.0 &amp;&amp; wave &lt;= 440.0) {
         r = -1.0 * (wave - 440.0) / (440.0 - 380.0);
         b = 1.0;
     } else if (wave &gt;= 440.0 &amp;&amp; wave &lt;= 490.0) {
         g = (wave - 440.0) / (490.0 - 440.0);
         b = 1.0;
     } else if (wave &gt;= 490.0 &amp;&amp; wave &lt;= 510.0) {
         g = 1.0;
         b = -1.0 * (wave - 510.0) / (510.0 - 490.0);
     } else if (wave &gt;= 510.0 &amp;&amp; wave &lt;= 580.0) {
         r = (wave - 510.0) / (580.0 - 510.0);
         g = 1.0;
     } else if (wave &gt;= 580.0 &amp;&amp; wave &lt;= 645.0) {
         r = 1.0;
         g = -1.0 * (wave - 645.0) / (645.0 - 580.0);
     } else if (wave &gt;= 645.0 &amp;&amp; wave &lt;= 780.0) {
         r = 1.0;
     }

     double s = 1.0;
     if (wave &gt; 700.0)
         s = 0.3 + 0.7 * (780.0 - wave) / (780.0 - 700.0);
     else if (wave &lt;  420.0)
         s = 0.3 + 0.7 * (wave - 380.0) / (420.0 - 380.0);

     r = pow(r * s, 0.8);
     g = pow(g * s, 0.8);
     b = pow(b * s, 0.8);
     return qRgb(int(r * 255), int(g * 255), int(b * 255));
 }</pre>
<p>The <tt>rgbFromWaveLength()</tt> function is a helper function that converts a wave length to a RGB value compatible with 32-bit <a href="qimage.html">QImage</a>s. It is called from the constructor to initialize the <tt>colormap</tt> array with pleasing colors.</p>
<a name="mandelbrotwidget-class-defintion"></a>
<h2>MandelbrotWidget Class Defintion</h2>
<p>The <tt>MandelbrotWidget</tt> class uses <tt>RenderThread</tt> to draw the Mandelbrot set on screen. Here's the class definition:</p>
<pre> class MandelbrotWidget : public QWidget
 {
     Q_OBJECT

 public:
     MandelbrotWidget(QWidget *parent = 0);

 protected:
     void paintEvent(QPaintEvent *event);
     void resizeEvent(QResizeEvent *event);
     void keyPressEvent(QKeyEvent *event);
     void wheelEvent(QWheelEvent *event);
     void mousePressEvent(QMouseEvent *event);
     void mouseMoveEvent(QMouseEvent *event);
     void mouseReleaseEvent(QMouseEvent *event);

 private slots:
     void updatePixmap(const QImage &amp;image, double scaleFactor);

 private:
     void zoom(double zoomFactor);
     void scroll(int deltaX, int deltaY);

     RenderThread thread;
     QPixmap pixmap;
     QPoint pixmapOffset;
     QPoint lastDragPos;
     double centerX;
     double centerY;
     double pixmapScale;
     double curScale;
 };</pre>
<p>The widget reimplements many event handlers from <a href="qwidget.html">QWidget</a>. In addition, it has an <tt>updatePixmap()</tt> slot that we'll connect to the worker thread's <tt>renderedImage()</tt> signal to update the display whenever we receive new data from the thread.</p>
<p>Among the private variables, we have <tt>thread</tt> of type <tt>RenderThread</tt> and <tt>pixmap</tt>, which contains the last rendered image.</p>
<a name="mandelbrotwidget-class-implementation"></a>
<h2>MandelbrotWidget Class Implementation</h2>
<pre> const double DefaultCenterX = -0.637011f;
 const double DefaultCenterY = -0.0395159f;
 const double DefaultScale = 0.00403897f;

 const double ZoomInFactor = 0.8f;
 const double ZoomOutFactor = 1 / ZoomInFactor;
 const int ScrollStep = 20;</pre>
<p>The implementation starts with a few contants that we'll need later on.</p>
<pre> MandelbrotWidget::MandelbrotWidget(QWidget *parent)
     : QWidget(parent)
 {
     centerX = DefaultCenterX;
     centerY = DefaultCenterY;
     pixmapScale = DefaultScale;
     curScale = DefaultScale;

     qRegisterMetaType&lt;QImage&gt;(&quot;QImage&quot;);
     connect(&amp;thread, SIGNAL(renderedImage(const QImage &amp;, double)),
             this, SLOT(updatePixmap(const QImage &amp;, double)));

     setWindowTitle(tr(&quot;Mandelbrot&quot;));
     setCursor(Qt::CrossCursor);
     resize(550, 400);
 }</pre>
<p>The interesting part of the constructor is the <a href="qmetatype.html#qRegisterMetaType">qRegisterMetaType</a>() and <a href="qobject.html#connect">QObject::connect</a>() calls. Let's start with the <a href="qobject.html#connect">connect()</a> call.</p>
<p>Although it looks like a standard signal-slot connection between two <a href="qobject.html">QObject</a>s, because the signal is emitted in a different thread than the receiver lives in, the connection is effectively a <a href="qt.html#ConnectionType-enum">queued connection</a>. These connections are asynchronous (i.e&#x2e;, non-blocking), meaning that the slot will be called at some point after the <tt>emit</tt> statement. What's more, the slot will be invoked in the thread in which the receiver lives. Here, the signal is emitted in the worker thread, and the slot is executed in the GUI thread when control returns to the event loop.</p>
<p>With queued connections, Qt must store a copy of the arguments that were passed to the signal so that it can pass them to the slot later on. Qt knows how to take of copy of many C++ and Qt types, but <a href="qimage.html">QImage</a> isn't one of them. We must therefore call the template function <a href="qmetatype.html#qRegisterMetaType">qRegisterMetaType</a>() before we can use <a href="qimage.html">QImage</a> as parameter in queued connections.</p>
<pre> void MandelbrotWidget::paintEvent(QPaintEvent * <span class="comment">/* event */</span>)
 {
     QPainter painter(this);
     painter.fillRect(rect(), Qt::black);

     if (pixmap.isNull()) {
         painter.setPen(Qt::white);
         painter.drawText(rect(), Qt::AlignCenter,
                          tr(&quot;Rendering initial image, please wait...&quot;));
         return;
     }</pre>
<p>In <a href="qwidget.html#paintEvent">paintEvent()</a>, we start by filling the background with black. If we have nothing yet to paint (<tt>pixmap</tt> is null), we print a message on the widget asking the user to be patient and return from the function immediately.</p>
<pre>     if (curScale == pixmapScale) {
         painter.drawPixmap(pixmapOffset, pixmap);
     } else {
         double scaleFactor = pixmapScale / curScale;
         int newWidth = int(pixmap.width() * scaleFactor);
         int newHeight = int(pixmap.height() * scaleFactor);
         int newX = pixmapOffset.x() + (pixmap.width() - newWidth) / 2;
         int newY = pixmapOffset.y() + (pixmap.height() - newHeight) / 2;

         painter.save();
         painter.translate(newX, newY);
         painter.scale(scaleFactor, scaleFactor);
         QRectF exposed = painter.matrix().inverted().mapRect(rect()).adjusted(-1, -1, 1, 1);
         painter.drawPixmap(exposed, pixmap, exposed);
         painter.restore();
     }</pre>
<p>If the pixmap has the right scale factor, we draw the pixmap directly onto the widget. Otherwise, we scale and translate the <a href="coordsys.html">coordinate system</a> before we draw the pixmap. By reverse mapping the widget's rectangle using the scaled painter matrix, we also make sure that only the exposed areas of the pixmap are drawn. The calls to <a href="qpainter.html#save">QPainter::save</a>() and <a href="qpainter.html#restore">QPainter::restore</a>() make sure that any painting performed afterwards uses the standard coordinate system.</p>
<pre>     QString text = tr(&quot;Use mouse wheel or the '+' and '-' keys to zoom. &quot;
                       &quot;Press and hold left mouse button to scroll.&quot;);
     QFontMetrics metrics = painter.fontMetrics();
     int textWidth = metrics.width(text);

     painter.setPen(Qt::NoPen);
     painter.setBrush(QColor(0, 0, 0, 127));
     painter.drawRect((width() - textWidth) / 2 - 5, 0, textWidth + 10,
                      metrics.lineSpacing() + 5);
     painter.setPen(Qt::white);
     painter.drawText((width() - textWidth) / 2,
                      metrics.leading() + metrics.ascent(), text);
 }</pre>
<p>At the end of the paint event handler, we draw a text string and a semi-transparent rectangle on top of the fractal.</p>
<pre> void MandelbrotWidget::resizeEvent(QResizeEvent * <span class="comment">/* event */</span>)
 {
     thread.render(centerX, centerY, curScale, size());
 }</pre>
<p>Whenever the user resizes the widget, we call <tt>render()</tt> to start generating a new image, with the same <tt>centerX</tt>, <tt>centerY</tt>, and <tt>curScale</tt> parameters but with the new widget size.</p>
<p>Notice that we rely on <tt>resizeEvent()</tt> being automatically called by Qt when the widget is shown the first time to generate the image the very first time.</p>
<pre> void MandelbrotWidget::keyPressEvent(QKeyEvent *event)
 {
     switch (event-&gt;key()) {
     case Qt::Key_Plus:
         zoom(ZoomInFactor);
         break;
     case Qt::Key_Minus:
         zoom(ZoomOutFactor);
         break;
     case Qt::Key_Left:
         scroll(-ScrollStep, 0);
         break;
     case Qt::Key_Right:
         scroll(+ScrollStep, 0);
         break;
     case Qt::Key_Down:
         scroll(0, -ScrollStep);
         break;
     case Qt::Key_Up:
         scroll(0, +ScrollStep);
         break;
     default:
         QWidget::keyPressEvent(event);
     }
 }</pre>
<p>The key press event handler provides a few keyboard bindings for the benefit of users who don't have a mouse. The <tt>zoom()</tt> and <tt>scroll()</tt> functions will be covered later.</p>
<pre> void MandelbrotWidget::wheelEvent(QWheelEvent *event)
 {
     int numDegrees = event-&gt;delta() / 8;
     double numSteps = numDegrees / 15.0f;
     zoom(pow(ZoomInFactor, numSteps));
 }</pre>
<p>The wheel event handler is reimplemented to make the mouse wheel control the zoom level. <a href="qwheelevent.html#delta">QWheelEvent::delta</a>() returns the angle of the wheel mouse movement, in eights of a degree. For most mice, one wheel step corresponds to 15 degrees. We find out how many mouse steps we have and determine the zoom factor in consequence. For example, if we have two wheel steps in the positive direction (i.e&#x2e;, +30 degrees), the zoom factor becomes <tt>ZoomInFactor</tt> to the second power, i.e&#x2e; 0.8 * 0.8 = 0.64.</p>
<pre> void MandelbrotWidget::mousePressEvent(QMouseEvent *event)
 {
     if (event-&gt;button() == Qt::LeftButton)
         lastDragPos = event-&gt;pos();
 }</pre>
<p>When the user presses the left mouse button, we store the mouse pointer position in <tt>lastDragPos</tt>.</p>
<pre> void MandelbrotWidget::mouseMoveEvent(QMouseEvent *event)
 {
     if (event-&gt;buttons() &amp; Qt::LeftButton) {
         pixmapOffset += event-&gt;pos() - lastDragPos;
         lastDragPos = event-&gt;pos();
         update();
     }
 }</pre>
<p>When the user moves the mouse pointer while the left mouse button is pressed, we adjust <tt>pixmapOffset</tt> to paint the pixmap at a shifted position and call <a href="qwidget.html#update">QWidget::update</a>() to force a repaint.</p>
<pre> void MandelbrotWidget::mouseReleaseEvent(QMouseEvent *event)
 {
     if (event-&gt;button() == Qt::LeftButton) {
         pixmapOffset += event-&gt;pos() - lastDragPos;
         lastDragPos = QPoint();

         int deltaX = (width() - pixmap.width()) / 2 - pixmapOffset.x();
         int deltaY = (height() - pixmap.height()) / 2 - pixmapOffset.y();
         scroll(deltaX, deltaY);
     }
 }</pre>
<p>When the left mouse button is released, we update <tt>pixmapOffset</tt> just like we did on a mouse move and we reset <tt>lastDragPos</tt> to a default value. Then, we call <tt>scroll()</tt> to render a new image for the new position. (Adjusting <tt>pixmapOffset</tt> isn't sufficient because areas revealed when dragging the pixmap are drawn in black.)</p>
<pre> void MandelbrotWidget::updatePixmap(const QImage &amp;image, double scaleFactor)
 {
     if (!lastDragPos.isNull())
         return;

     pixmap = QPixmap::fromImage(image);
     pixmapOffset = QPoint();
     lastDragPos = QPoint();
     pixmapScale = scaleFactor;
     update();
 }</pre>
<p>The <tt>updatePixmap()</tt> slot is invoked when the worker thread has finished rendering an image. We start by checking whether a drag is in effect and do nothing in that case. In the normal case, we store the image in <tt>pixmap</tt> and reinitialize some of the other members. At the end, we call <a href="qwidget.html#update">QWidget::update</a>() to refresh the display.</p>
<p>At this point, you might wonder why we use a <a href="qimage.html">QImage</a> for the parameter and a <a href="qpixmap.html">QPixmap</a> for the data member. Why not stick to one type? The reason is that <a href="qimage.html">QImage</a> is the only class that supports direct pixel manipulation, which we need in the worker thread. On the other hand, before an image can be drawn on screen, it must be converted into a pixmap. It's better to do the conversion once and for all here, rather than in <tt>paintEvent()</tt>.</p>
<pre> void MandelbrotWidget::zoom(double zoomFactor)
 {
     curScale *= zoomFactor;
     update();
     thread.render(centerX, centerY, curScale, size());
 }</pre>
<p>In <tt>zoom()</tt>, we recompute <tt>curScale</tt>. Then we call <a href="qwidget.html#update">QWidget::update</a>() to draw a scaled pixmap, and we ask the worker thread to render a new image corresponding to the new <tt>curScale</tt> value.</p>
<pre> void MandelbrotWidget::scroll(int deltaX, int deltaY)
 {
     centerX += deltaX * curScale;
     centerY += deltaY * curScale;
     update();
     thread.render(centerX, centerY, curScale, size());
 }</pre>
<p><tt>scroll()</tt> is similar to <tt>zoom()</tt>, except that the affected parameters are <tt>centerX</tt> and <tt>centerY</tt>.</p>
<a name="the-main-function"></a>
<h2>The main() Function</h2>
<p>The application's multithreaded nature has no impact on its <tt>main()</tt> function, which is as simple as usual:</p>
<pre> int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);
     MandelbrotWidget widget;
     widget.show();
     return app.exec();
 }</pre>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright &copy; 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.5</div></td>
</tr></table></div></address></body>
</html>
